package com.fh.alipay.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Objects;

/**
 * @FileName: FileCommonUtil
 * @Author: fh
 * @Date: 2021/12/13 15:15
 * @Description: 文件工具
 * @Version: 1.0
 */
@Slf4j
public class FileCommonUtil {

    /**
     * MultipartFile 转 File
     *
     * @param multipartFile 参数
     * @return file
     */
    public static File transferToFile(MultipartFile multipartFile) {
        File toFile = null;
        if (multipartFile.isEmpty()) {
            multipartFile = null;
        } else {
            InputStream ins = null;
            try {
                ins = multipartFile.getInputStream();
                toFile = new File(Objects.requireNonNull(multipartFile.getOriginalFilename()));
                inputStreamToFile(ins, toFile);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != ins) {
                        ins.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return toFile;
    }

    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 删除文件
     *
     * @param files
     */
    public static void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }

}
